﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Configuration;
using System.Web.Configuration;

namespace CNRS.CCP.Connector
{
    // TODO: still used ?
    public class ConfigFileHelper
    {
        public static string getValueFromWebConfig(string key)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
            AppSettingsSection appSettings = config.AppSettings;
            if (appSettings == null)
                throw new ApplicationException("Web.config appSettings section cannot be found!");
            if (appSettings.Settings[key] == null || string.IsNullOrEmpty(appSettings.Settings[key].Value))
                throw new ApplicationException("Key value cannot be read from appSettings. Make sure this key and its value exist!");

            return appSettings.Settings[key].Value;
        }

        public static void changeConfig(string path, string key, string value)
        {
            try
            {
                //Creation du filestream (fs)
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //Creation du document xml
                System.Xml.XmlDocument CXML = new System.Xml.XmlDocument();

                //Charge le document xml
                CXML.Load(fs);

                //Ferme le filestream
                fs.Close();

                //Récupère le noeud parent
                XmlNode appSettings = CXML.GetElementsByTagName("appSettings").Item(0);

                //Verifie l'existence du noeud cible
                XmlNode node = appSettings.SelectSingleNode("add[@key='" + key + "']");

                if (node == null)
                {
                    //Création du nouveau noeud
                    XmlElement newitem = CXML.CreateElement("add");

                    //Creation du nouveau contenu xml
                    XmlAttribute xmlKey = CXML.CreateAttribute("key");
                    xmlKey.InnerText = key;

                    XmlAttribute xmlValue = CXML.CreateAttribute("value");
                    xmlValue.InnerText = value;

                    //Insert les attributs xml
                    newitem.Attributes.Append(xmlKey);
                    newitem.Attributes.Append(xmlValue);

                    //Insert le nouvel element xml dans le document xml(CXML)
                    appSettings.InsertAfter(newitem, appSettings.LastChild);
                }
                else
                {
                    node.Attributes["value"].InnerText = value;
                }

                //Sauvegarde le fichier XML
                FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
                CXML.Save(WRITER);

                //Ferme le writer filestream
                WRITER.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Une erreur est survenue : " + ex.Message);
            }
        }
    }
}
